<template>
  <div class="content">
    <el-row>
      <el-form ref="searchForm" :model="formData" label-width="70px" :rules="rules">
        <el-col :lg="6">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="formData.name" placeholder="请输入姓名" maxlength="10" clearable
                      :style="{width: '100%'}"/>
          </el-form-item>
        </el-col>
        <el-col :lg="6">
          <el-form-item label="学院" prop="collegeId">
            <el-select v-model="formData.collegeId" placeholder="请选择学院" clearable :style="{width: '100%'}"
                       @change="checkedCollege">
              <el-option
                v-for="(item, index) in collegeIdOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :lg="6">
          <el-form-item label="年级" prop="grade">
            <el-input v-model="formData.grade" placeholder="请输入年级" maxlength="50" clearable
                      :style="{width: '100%'}"/>
          </el-form-item>
        </el-col>
        <el-col :lg="6">
          <el-form-item label="班级" prop="classId">
            <el-select v-model="formData.classId" placeholder="请选择班级" clearable :style="{width: '100%'}"
                       :no-data-text="noDataText">
              <el-option
                v-for="(item, index) in classIdOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :lg="6">
          <el-form-item label="学号" prop="stuNum">
            <el-input v-model="formData.stuNum" placeholder="请输入学号" maxlength="20" clearable
                      :style="{width: '100%'}"/>
          </el-form-item>
        </el-col>
        <el-col :lg="6">
          <el-form-item label="手机号" prop="phoneNumber">
            <el-input v-model="formData.phoneNumber" placeholder="请输入手机号" maxlength="11" clearable
                      :style="{width: '100%'}"/>
          </el-form-item>
        </el-col>
        <el-col :lg="6" style="text-align: center">
          <el-button class="submit" @click="resetForm">重置</el-button>
          <el-button type="primary" class="submit" @click="search('searchForm')">搜索</el-button>
        </el-col>
      </el-form>
    </el-row>
    <div class="redact">
      <el-button v-hasPermi="['student:add']" type="primary" @click="add">添加</el-button>
      <el-button v-hasPermi="['student:add']" type="primary" @click="lead">导入</el-button>
      <el-button v-hasPermi="['student:export']" type="primary"  @click="exportStu">导出
      </el-button>
      <el-button v-hasPermi="['student:export']" type="primary" @click="exportAll">全部导出</el-button>
    </div>
    <!--    表格部分-->
    <div>
      <el-table
        ref="multipleTable"
        v-loading="loading"
        border
        :data="tableData"
        tooltip-effect="dark"
        @select="checked"
        @select-all="checkedAll"
      >
        <el-table-column
          type="selection"
        />
        <el-table-column
          label="序号"
          prop="order"
          fixed="left"
        />
        <el-table-column
          label="姓名"
        >
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="scope.row.name" placement="top" :enterable="false"
            >
              <span style="cursor: default;white-space: nowrap">{{ scope.row.name }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          label="学院"
        >
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="scope.row.college" placement="top" :enterable="false"
            >
              <span style="cursor: default;white-space: nowrap">{{ scope.row.college }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          prop="grade"
          label="年级"
        />
        <el-table-column
          label="班级"
        >
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="scope.row.className" placement="top" :enterable="false"
            >
              <span style="cursor: default;white-space: nowrap">{{ scope.row.className }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          prop="stuNum"
          label="学号"
        />
        <el-table-column
          prop="phoneNumber"
          label="手机号"
        />
        <el-table-column
          label="入学日期"
          prop="enrollmentTime"
        />
        <el-table-column label="操作" min-width="140" fixed="right">
          <template slot-scope="scope">
            <el-button v-hasPermi="['student:edit']" type="text" @click="editStu(scope.row)"><i class="el-icon-edit"/>编辑
            </el-button>
            <el-button v-hasPermi="['student:psychometric']" type="text" @click="put1(scope.row)"><i
              class="el-icon-document"/>普测信息
            </el-button>
            <el-button v-hasPermi="['student:remove']" type="text" @click="deleteInformation(scope.row.id)"><i
              class="el-icon-delete"/>删除
            </el-button>
            <router-link v-hasPermi="['student:record']"
                         :to="{path:'/record/',query:{id:scope.row.id,stuNum:scope.row.stuNum}}"
                         style="padding: 0 10px;">
              <el-button type="text"><i
                class="el-icon-paperclip"
              />心理档案
              </el-button>
            </router-link>
            <el-button
              v-hasPermi="['student:resetPwd']"
              type="text"
              @click="stuResetPwd(scope.row)"
            >
              <i class="el-icon-key"/>
              重置密码
            </el-button>
            <!--            <el-button type="text" @click="dailyback(scope.row.id)" v-hasPermi="['student:feedback']"><i class="el-icon-chat-line-square"></i>日常反馈</el-button>-->
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--底部分页-->
    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :total=total
        hide-on-single-page
        :current-page=pageNum
        @current-change="changeCurrent"
      />
    </div>
    <!--    添加学生-->
    <el-dialog :visible.sync="dialogTableVisibleAdd" :close-on-click-modal="false" :show-close="false" width="800px">
      <div class="dialogWhiteTitle">
        {{ dialogTitle }}
        <div class="close" @click="dialogTableVisibleAdd=false">
          <i class="el-icon-close"/>
        </div>
      </div>
      <div class="addStudent">
        <add ref="addstu" :stu-imformation="stuImformation" :is-edit="isEdit"
             :dialog-table-visible-add="dialogTableVisibleAdd" @closeAdd="closeAdd" @AddOK="AddOK" @editOK="editOK"/>
      </div>
    </el-dialog>
    <!--    学生导入-->
    <el-dialog width="402px" :visible.sync="dialogTableVisibleLead" :show-close="false">
      <div style="display: flex; flex-direction:column;justify-content: center;align-items: center;flex-wrap: wrap">
        <div class="dialogWhiteTitle">
          学生导入
          <div class="close" @click="dialogTableVisibleLead=false">
            <i class="el-icon-close"/>
          </div>
        </div>
        <lead @success="resetForm"/>
        <div style="padding: 20px">
          <el-button @click="dialogTableVisibleLead = false">取 消</el-button>
          <el-button type="primary" @click="dialogTableVisibleLead = false">确 定</el-button>
        </div>
      </div>
    </el-dialog>
    <!--   普测信息 -->
    <el-dialog
      :visible.sync="dialogTableVisiblePut"
      width="700px"
      :show-close="false"
      center
    >
      <div class="dialogTitle">
        普测信息
        <div class="close" @click="dialogTableVisiblePut=false">
          <i class="el-icon-close"/>
        </div>
      </div>
      <div class="textArea">
        <el-input
          v-model="psychometricTest"
          type="textarea"
          :rows="12"
          placeholder="请填写普测信息"
          :maxlength="200"
          resize="none"
          show-word-limit
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisiblePut = false">取 消</el-button>
        <el-button type="primary" @click="submitPsychometricTest">保 存</el-button>
      </span>
    </el-dialog>
    <!--    日常反馈信息-->
    <el-dialog
      :visible.sync="dialogTableVisibleDailyback"
      width="700px"
      :show-close="false"
      center
    >
      <div class="dialogTitle">
        日常反馈信息
        <div class="close" @click="dialogTableVisibleDailyback=false">
          <i class="el-icon-close"/>
        </div>
      </div>
      <div class="textArea">
        <el-input
          v-model="feedback"
          type="textarea"
          :rows="12"
          placeholder="请填写日常反馈信息"
          :maxlength="500"
          show-word-limit
          resize="none"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisibleDailyback = false">取 消</el-button>
        <el-button type="primary" @click="DailybackOK">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import add from '@/components/Student/AddStudent/index'
import lead from '@/components/Student/ToLead/index'
import {
  classList,
  collegeList,
  getStudentList,
  addStu,
  deleteStu,
  changeStu,
  updataFeedback,
  stuResetPwdApi,
  leadstu,
  leadAll
} from '@/api/sdutent/Stulist'

export default {
  name: 'Index',
  components: {
    add,
    lead
  },
  data() {
    var mobileTest = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else if (!this.mobileRef.test(value)) {
        callback(new Error('手机号格式错误!'))
      } else {
        callback()
      }
    }
    var stuNumTest = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else if ((!this.stuNumRef.test(value))) {
        callback(new Error('学号格式错误!'))
      } else {
        callback()
      }
    }
    var gradeTest = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else if ((!this.gradeRef.test(value))) {
        callback(new Error('年级只能是数字!'))
      } else {
        callback()
      }
    }
    var nameTest = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else if ((this.nameRef.test(value))) {
        callback(new Error('姓名不能含有特殊字符!'))
      } else if ((this.punctuationRef.test(value))) {
        callback(new Error('姓名不能包含标点符号!'))
      } else {
        callback()
      }
    }
    return {
      mobileRef: /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/,
      stuNumRef: /^[0-9]{2}([0-9]|L){1}[0-9]{7}$/,
      gradeRef: /^[0-9]{1,}$/,
      nameRef: /[\x20-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]+/,
      punctuationRef: /\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5/,
      loading: true,
      pageNum: 1,
      stuImformation: {},
      isEdit: false,
      feedback: '',
      stuid: 0,
      total: 0,
      collegeIdOptions: [],
      classIdOptions: [],
      psychometricTest: '',
      // 添加弹出框
      dialogTableVisibleAdd: false,
      // 导入弹出框
      dialogTableVisibleLead: false,
      dialogTableVisiblePut: false,
      dialogTableVisibleDailyback: false,
      // 添加/编辑弹出框表头文本
      dialogTitle: '添加学生',
      // 班级无数据时显示数据
      noDataText: '请先选择学院',
      rules: {
        grade: [{
          validator: gradeTest,
          trigger: 'blur'
        }
        ],
        name: [{
          validator: nameTest,
          trigger: 'change'
        }
        ],
        stuNum: [{
          pattern: /^[0-9]+$/,
          message: '学号格式错误',
          trigger: 'blur'
        }],
        phoneNumber: [
          {
            validator: mobileTest,
            trigger: 'blur'
          }
        ]
      },
      // 模拟数据
      tableData: [],
      ids: [],
      newFormData: {
        name: '', // 姓名
        collegeId: '', // 学院
        grade: '', // 年级
        classId: '', // 班级
        stuNum: '', // 学号
        education: '', // 学历
        phoneNumber: '', // 手机号
        status: '', // 状态
        enrollmentTime: '', // 入学时间
        anamnesis: '', // 既往病史
        experience: '', // 心理诊断
        medicationSituation: '', // 服药情况
        familyInfo: '', // 家庭情况
        remark: '', // 其他
        psychometricTest: '', // 心理普测
        gender: '',
        birthday: '',
        id: '',
        nickname: '',
        avatar: '',
        password: ''
      },
      query: {
        pageSize: 10,
        pageNum: 1,
        name: '',
        collegeId: '', // 年级
        grade: '',
        stuNum: '',
        phoneNumber: ''
      },
      formData: {
        name: '',
        collegeId: '', // 年级
        classId: '',
        grade: '',
        stuNum: '',
        phoneNumber: ''
      }
    }
  },
  created() {
    // 获取班级列表
    collegeList().then(res => {
      if (res.code == 200) {
        res.data.forEach(item => {
          this.collegeIdOptions.push({label: item.deptName, value: item.deptId})
        })
      }
    })
    this.feedback
    this.submitForm(this.query)
  },
  methods: {
    // 重置密码
    stuResetPwd(item) {
      this.$confirm(`此操作将重置学生:${item.name},密码为学号，是否继续？`, '提示', {
        confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        stuResetPwdApi(item.id).then(res => {
          if (res.code === 200) {
            this.$modal.msgSuccess('修改成功，新密码为该学生学号')
          }
        })
      })
    },
    exportAll() {
      // this.download('/system/student/export',{},'学生导出数据.xlsx')
      leadAll().then(res => {
        const fileData = res
        const url = window.URL.createObjectURL(new Blob([fileData], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', '学生导出数据.xlsx')
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
      })
    },
    exportStu() {
      leadstu(this.ids).then(res => {
          const fileData = res
          const url = window.URL.createObjectURL(new Blob([fileData], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}))
          const link = document.createElement('a')
          link.href = url
          link.setAttribute('download', '学生导出数据.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          window.URL.revokeObjectURL(url)
        }
      )
    },
    // 点击多选框
    checked(selection) {
      this.importData(selection)
    },
    checkedAll(selection) {
      this.importData(selection)
    },
    // 重置搜索信息
    resetFormData() {
      for (const i in this.formData) {
        this.formData[i] = ''
        this.query[i] = this.formData[i]
      }
    },
    // 添加学生取消按钮
    closeAdd() {
      this.dialogTableVisibleAdd = false
    },
    // 部分导出数据
    importData(array) {
      this.exportData = []
      this.ids = []
      array.forEach(item => {
        this.ids.push(item.id)
      })
    },
    // 添加学生信息
    AddOK(form) {
      addStu(form).then(res => {
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: '添加成功'
          })
          this.resetFormData()
          this.submitForm(this.query, 1)
          this.dialogTableVisibleAdd = false
        } else {
          this.$message({
            type: 'error',
            message: '添加失败'
          })
        }
      })
    },
    // 编辑学生信息
    editStu(stuImformation) {
      this.dialogTitle = '编辑学生'
      this.isEdit = stuImformation.id
      this.dialogTableVisibleAdd = true
      for (const i in stuImformation) {
        if (stuImformation[i] == '暂无数据') {
          stuImformation[i] = null
        }
      }
      this.stuImformation = stuImformation
    },
    // 提交编辑信息
    editOK(form) {
      this.$confirm('是否确认修改该学生信息', '提示', {
        confirmButtonText: '修改',
        cancelButtonText: '取消'
      }).then(() => {
        changeStu(form).then(res => {
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '修改成功'
            })
            this.dialogTableVisibleAdd = false
            this.submitForm(this.query, this.pageNum)
          } else {
            this.$message({
              type: 'error',
              message: '修改失败'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消修改'
        })
      })
    },
    // 删除信息
    deleteInformation(id) {
      this.$confirm('此操作将永久删除该学生信息，是否继续？', '提示', {
        confirmButtonText: '删除', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        deleteStu([id]).then(res => {
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: '删除成功'
            })
            if (this.pageNum == Math.ceil(this.total / 10)) {
              if (this.total % 10 == 1) {
                this.pageNum--
              }
            }
            this.submitForm(this.query, this.pageNum)
          } else {
            this.$message({
              type: 'error',
              message: '删除失败'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 添加学生
    add() {
      this.isEdit = ''
      this.dialogTitle = '添加学生'
      this.dialogTableVisibleAdd = true
    },
    // 导入学生
    lead() {
      this.dialogTableVisibleLead = true
    },
    // 触发日常反馈
    dailyback(data) {
      this.feedback = ''
      this.stuid = data
      this.dialogTableVisibleDailyback = true
    },
    // 提交日常反馈
    DailybackOK() {
      if (this.feedback.length > 0) {
        updataFeedback({studentId: this.stuid, content: this.feedback}).then(res => {
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: '添加成功'
            })
            this.dialogTableVisibleDailyback = false
          } else {
            this.$message({
              type: 'error',
              message: '添加失败'
            })
          }
        })
      } else {
        this.$message({
          type: 'error',
          message: '请您输入内容后添加'
        })
      }
    },
    // 触发普测信息
    put1(data) {
      this.psychometricTest = data.psychometricTest
      for (const key1 in this.newFormData) {
        for (const key2 in data) {
          if (key1 == key2) {
            this.newFormData[key1] = data[key1]
          }
        }
      }
      this.dialogTableVisiblePut = true
    },
    // 提交普测信息
    submitPsychometricTest(data) {
      if (this.newFormData.psychometricTest == this.psychometricTest) {
        this.dialogTableVisiblePut = false
      } else {
        this.$confirm('是否更改普测信息', '提示', {
          cancelButtonText: '取消',
          confirmButtonText: '修改',
          type: 'warning'
        }).then(() => {
          this.newFormData.psychometricTest = this.psychometricTest
          changeStu(this.newFormData).then(res => {
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: '修改成功'
              })
              this.submitForm(this.query, this.pageNum)
              this.dialogTableVisiblePut = false
            } else {
              this.$message({
                type: 'error',
                message: '修改失败'
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消修改'
          })
        })
      }
    },
    // 请求学生列表
    submitForm(query, page = 1, pageSize = 10) {
      this.loading = true
      this.tableData = []
      query.pageNum = page
      query.pageSize = pageSize
      getStudentList(query).then(res => {
        if (res.code === 200) {
          this.total = Number(res.total)
          this.pageNum = page
          res.rows.forEach((item, index) => {
            item.order = index + 1 + (page - 1) * 10
            this.tableData.push(item)
          })
          this.loading = false
          this.dialogTableVisibleLead = false
        }
        // console.log(this.tableData)
      })
    },
    // 重置学生列表
    resetForm() {
      this.resetFormData()
      this.noDataText = '请先选择学院'
      this.classIdOptions = []
      this.submitForm(this.query)
    },
    //  改变页数
    changeCurrent(pageNum) {
      this.submitForm(this.query, pageNum)
    },
    // 获取班级列表
    getClassList(deptId) {
      const queryParams = {
        pageNum: 1,
        pageSize: 999,
        deptId: deptId
      }
      classList(queryParams).then(res => {
        if (res.code === 200) {
          this.classIdOptions = []
          this.noDataText = '无数据'
          res.rows.forEach(item => {
            this.classIdOptions.push({label: item.name, value: item.id})
          })
          this.loading = false
        }
      })
    },
    // 选择学院获取班级
    checkedCollege(value) {
      this.noDataText = '请先选择学院'
      this.classIdOptions = []
      this.formData.classId = ''
      if (value) {
        this.query.deptId = value
        this.getClassList(value)
      }
    },
    // 搜索
    search(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          for (const i in this.formData) {
            this.query[i] = this.formData[i]
          }
          this.submitForm(this.query)
        } else {
          return false
        }
      })
    }
  }
}

</script>
<style scoped>
.content {
  padding: 26px 25px;
  width: 100%;
}

.submit {
  margin-left: 7px;
}

.redact {
  margin: 10px 0 20px;
}

.pagination {
  padding: 20px 0;
  float: right;
}

.el-table__header {
  width: 100% !important;
}

.el-table__body {
  width: 100% !important;
}

/deep/ .el-dialog__header {
  padding: 0 !important;
}

/deep/ .el-dialog__body {
  padding: 0 !important;
}

.textArea {
  padding: 30px;
}

.dialogTitle {
  padding: 11px 0 12px 26px;
  background-color: #1892ff;
  color: white;
  position: relative;
  width: 100%;
}

.close {
  position: absolute;
  right: 22px;
  top: 13px;
}

.dialogWhiteTitle {
  position: relative;
  width: 100%;
  padding: 13px 0 42px 26px;
  font-size: 18px;
}

.addStudent {
  padding: 0 30px;
}
</style>

